<template>
  <div class="video-card" @click="navigateToVideo">
    <div class="thumbnail-container">
      <img :src="getThumbnailUrl(video.thumbnail)" :alt="video.title" class="thumbnail" />
      <span class="duration">{{ formatDuration(video.duration) }}</span> <!-- 修改：格式化时长 -->
    </div>
    <div class="video-info">
      <div class="user-avatar">
        <!-- 修改：仅在用户有头像时显示头像 -->
        <el-avatar v-if="video.user?.avatar" :size="40" :src="getImageUrl(video.user.avatar)"></el-avatar>
        <!-- 可以选择添加一个占位符或图标，如果希望在没有头像时显示点什么 -->
        <el-avatar v-else :size="40"><User /></el-avatar>
      </div>
      <div class="video-details">
        <h3 class="video-title" :title="video.title">{{ video.title }}</h3>
        <!-- 修改：确保 user 存在，并使用 username -->
        <p class="channel-name">{{ video.user?.username || '未知用户' }}</p>
        <p class="video-stats">
          {{ formatViews(video.views) }} 次观看 · {{ formatDate(video.createdAt) }}
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue' // 导入用户图标作为头像占位符

const props = defineProps({
  video: {
    type: Object,
    required: true,
    default: () => ({
      _id: '',
      title: '',
      thumbnail: '',
      duration: 0,
      views: 0,
      createdAt: new Date(),
      user: {
        _id: '',
        avatar: null, 
        username: '未知用户'
      }
    })
  }
})

const router = useRouter()

// 格式化观看次数
const formatViews = (views) => {
  if (views >= 1000000) {
    return (views / 1000000).toFixed(1) + '百万'
  } else if (views >= 10000) {
    return (views / 10000).toFixed(1) + '万'
  } else if (views >= 1000) {
    return (views / 1000).toFixed(1) + '千'
  } else {
    return views
  }
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffTime = Math.abs(now - date)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 1) {
    return '1 天前'
  } else if (diffDays < 7) {
    return diffDays + ' 天前'
  } else if (diffDays < 30) {
    const weeks = Math.floor(diffDays / 7)
    return weeks + ' 周前'
  } else if (diffDays < 365) {
    const months = Math.floor(diffDays / 30)
    return months + ' 个月前'
  } else {
    const years = Math.floor(diffDays / 365)
    return years + ' 年前'
  }
}

// 添加：格式化时长函数
const formatDuration = (seconds) => {
  if (isNaN(seconds) || seconds < 0) {
    return '00:00';
  }
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.floor(seconds % 60);
  const formattedMinutes = String(minutes).padStart(2, '0');
  const formattedSeconds = String(remainingSeconds).padStart(2, '0');
  return `${formattedMinutes}:${formattedSeconds}`;
};

// 添加：获取完整的缩略图URL
const getThumbnailUrl = (relativePath) => {
  if (!relativePath) return '/default-thumbnail.jpg'; // 提供默认封面
  if (relativePath.startsWith('http')) return relativePath; // 已经是完整URL
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000';
  return `${baseUrl}${relativePath}`;
};

// 添加：获取完整的图片URL（用于头像等）
const getImageUrl = (relativePath) => {
  if (!relativePath) return null; // 不再提供默认头像
  if (relativePath.startsWith('http')) return relativePath;
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000';
  return `${baseUrl}${relativePath}`;
};

// 导航到视频详情页
const navigateToVideo = () => {
  // 增强ID验证，检查是否为undefined、null、空字符串或'undefined'字符串
  if (!props.video?._id || props.video._id === 'undefined' || props.video._id === '') {
    console.error('无效的视频ID:', props.video);
    ElMessage.error('无法访问视频详情，视频ID无效');
    return;
  }
  
  // 确保ID是有效的MongoDB ObjectId格式（24位十六进制字符串）
  const objectIdPattern = /^[0-9a-fA-F]{24}$/;
  if (!objectIdPattern.test(props.video._id)) {
    console.error('视频ID格式无效:', props.video._id);
    ElMessage.error('无法访问视频详情，ID格式错误');
    return;
  }
  
  router.push(`/video/${props.video._id}`);
};
</script>

<style scoped>
.video-card {
  cursor: pointer;
  margin-bottom: 20px;
  transition: transform 0.2s;
}

.video-card:hover {
  transform: translateY(-5px);
}

.thumbnail-container {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%; /* 16:9 宽高比 */
  overflow: hidden;
  border-radius: 8px;
}

.thumbnail {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2px 4px;
  border-radius: 4px;
  font-size: 12px;
}

.video-info {
  display: flex;
  margin-top: 12px;
}

.user-avatar {
  margin-right: 12px;
}

.video-details {
  flex: 1;
  overflow: hidden;
}

.video-title {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 500;
  line-height: 1.4;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.channel-name {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #606060;
}

.video-stats {
  margin: 0;
  font-size: 14px;
  color: #606060;
}
</style>